package com.future.hedongjun.mall.activity;

import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.future.baselib.activity.BaseActivity;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.http.HttpRequest;
import com.future.baselib.utils.FullyLinearLayoutManager;
import com.future.baselib.utils.GlideUtils;
import com.future.baselib.view.CircleImageView;
import com.future.baselib.view.CustomViewBottomDialog;
import com.future.hedongjun.R;
import com.future.hedongjun.common.MyApp;
import com.future.hedongjun.common.PriceHelper;
import com.future.hedongjun.home.utils.GlideImageLoader;
import com.future.hedongjun.mall.adapter.GoodsTypeAdapter;
import com.future.hedongjun.mall.bean.EvaluateBean;
import com.future.hedongjun.mall.bean.GoodsDetail;
import com.future.hedongjun.mall.bean.GoodsDetailResponse;
import com.future.hedongjun.mine.ui.LoginActivity;
import com.wuhenzhizao.sku.view.SkuSelectScrollView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GoodsDetailActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.iv_shopping_car)
    ImageView ivShoppingCar;
    @BindView(R.id.tv_evaluate_count)
    TextView tvEvaluateCount;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.tv_goods_title)
    TextView tvGoodsTitle;
    @BindView(R.id.iv_evaluate_person_icon)
    CircleImageView ivEvaluatePersonIcon;
    @BindView(R.id.tv_evaluate_person_name)
    TextView tvEvaluatePersonName;
    @BindView(R.id.tv_evaluate_person_time)
    TextView tvEvaluatePersonTime;
    @BindView(R.id.tv_evaluate_content)
    TextView tvEvaluateContent;
    @BindView(R.id.layout_evaluate)
    RelativeLayout layoutEvaluate;
    @BindView(R.id.webView_goods_detail)
    WebView webViewGoodsDetail;
    @BindView(R.id.btn_add_shopping_car)
    Button btnAddShoppingCar;
    @BindView(R.id.btn_buy_now)
    Button btnBuyNow;
    @BindView(R.id.layout_no_evaluate)
    RelativeLayout layoutNoEvaluate;
    @BindView(R.id.tv_postage)
    TextView tvPostage;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    private String id;
    private RecyclerView recyclerView;
    private TextView tvCount;
    private CustomViewBottomDialog typeDialog;
    private int dialogType;
    private Button btnOk;
    private GoodsDetail goodsDetail;
    private GoodsDetail.SpecData specData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
        ButterKnife.bind(this);

        setTitle("商品详情");
        getDetail();
//        updateView(initTestData());
    }

    private void updateView(GoodsDetail detail) {
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR);
        banner.setImageLoader(new GlideImageLoader());

        banner.setImages(detail.getImgs_url());
        //banner设置方法全部调用完毕时最后调用
        banner.start();

        tvGoodsTitle.setText(detail.getGoods_name());
        tvPrice.setText(PriceHelper.priceFormat(specData.getSpec_list().get(0).getForm().getGoods_price()));
        tvPostage.setText(PriceHelper.priceFormat(5.0));//邮费
//         //评价
//        int size = detail.evaluateBeans.size();
//        if (size == 0) {
//            layoutEvaluate.setVisibility(View.GONE);
//            layoutNoEvaluate.setVisibility(View.VISIBLE);
//        } else {
//            layoutEvaluate.setVisibility(View.VISIBLE);
//            layoutNoEvaluate.setVisibility(View.GONE);
//            tvEvaluateCount.setText("评论(" + size + ")");
//            EvaluateBean bean = detail.evaluateBeans.get(0);
//            tvEvaluatePersonTime.setText(bean.time);
//            tvEvaluatePersonName.setText(bean.name);
//            tvEvaluateContent.setText(bean.content);
//            GlideUtils.loadImage(this, bean.imgUrl, ivEvaluatePersonIcon);
//        }
        webViewGoodsDetail.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                imgReset();
            }
        });
        webViewGoodsDetail.setWebChromeClient(new WebChromeClient());
        WebSettings settings = webViewGoodsDetail.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setBuiltInZoomControls(true);
        webViewGoodsDetail.loadData(detail.getContent(), "text/html; charset=UTF-8", "");
    }

    private void imgReset() {
        webViewGoodsDetail.loadUrl("javascript:(function(){" +
                        "var objs = document.getElementsByTagName('img'); " +
                        "for(var i=0;i<objs.length;i++)  " +
                        "{"
                        + "var img = objs[i];   " +
                        "    img.style.maxWidth = '100%'; img.style.height = 'auto';  " +
                        "}" +
                        "})()");
    }

    public GoodsDetail initTestData() {
        GoodsDetail detail = new GoodsDetail();
        ArrayList<String> imageUrls = new ArrayList<>();
        imageUrls.add("http://seopic.699pic.com/photo/50025/2423.jpg_wh1200.jpg");
        imageUrls.add("http://seopic.699pic.com/photo/50025/2423.jpg_wh1200.jpg");
        imageUrls.add("http://seopic.699pic.com/photo/50025/2423.jpg_wh1200.jpg");
//        detail.imgUrls = imageUrls;
//        detail.goodsTitle = "商品标题商品标题商品标题商品标题商品标题";
//        detail.goodsPrice = 100.00;
//        detail.evaluateCount = 20;
//        detail.evaluatePersonIcon = "http://seopic.699pic.com/photo/50025/2423.jpg_wh1200.jpg";
//        detail.evaluatePersonName = "评论人昵称";
//        detail.evaluatePersonTime = "11-19 10:00";
//        detail.evaluateContent = "评论内容内容内容";
//        detail.detailUrl = "http://www.baidu.com";
        return detail;
    }

    private void getDetail() {
        new HttpRequest<GoodsDetailResponse>()
                .with(this)
                .setPath("/addons/litestore/api.goods/detail")
                .addParam("goods_id", id)
                .addSuccessListener(new HttpRequest.OnNetworkSuccess<GoodsDetailResponse>() {
                    @Override
                    public void onSuccess(GoodsDetailResponse response) {
                        goodsDetail = response.goodsDetail;
                        specData = response.specData;
                        updateView(goodsDetail);
                    }
                })
                .addFailListener(new HttpRequest.OnNetworkFail() {
                    @Override
                    public void onFail(String message) {

                    }
                }).start(new GoodsDetailResponse());
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        id = extras.getString("id");
    }

    @OnClick({R.id.layout_evaluate, R.id.iv_shopping_car, R.id.btn_add_shopping_car, R.id.btn_buy_now})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_evaluate:
                Bundle bundle = new Bundle();
                bundle.putString("id", id);
                startActivity(EvaluateActivity.class, bundle);
                break;
            case R.id.btn_add_shopping_car:
                if (MyApp.getInstance().hasLogin()) {
                    showTypesDialog(1);
                } else {
                    startActivity(LoginActivity.class);
                }
                break;
            case R.id.btn_buy_now:
                if (MyApp.getInstance().hasLogin()) {
                    showTypesDialog(2);
                } else {
                    startActivity(LoginActivity.class);
                }
                break;
            case R.id.iv_shopping_car:
                if (MyApp.getInstance().hasLogin()) {
                    startActivity(ShoppingCarActivity.class);
                } else {
                    startActivity(LoginActivity.class);
                }
                break;
        }
    }

    public void showTypesDialog(int type) {
        SkuSelectScrollView selectScrollView = new SkuSelectScrollView(this);
        if (typeDialog == null) {
            View view = getLayoutInflater().inflate(R.layout.dialog_goods_types, null);
            view.findViewById(R.id.iv_close).setOnClickListener(this);
            view.findViewById(R.id.iv_minus).setOnClickListener(this);
            view.findViewById(R.id.iv_add).setOnClickListener(this);
            btnOk = (Button) view.findViewById(R.id.btn_ok);
            btnOk.setOnClickListener(this);
            recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
            recyclerView.setLayoutManager(new FullyLinearLayoutManager(this));
            recyclerView.setAdapter(new GoodsTypeAdapter(null));
            tvCount = (TextView) view.findViewById(R.id.tv_count);
            typeDialog = new CustomViewBottomDialog(this)
                    .setView(view)
                    .builder();
        }
        btnOk.setText(type == 1 ? "加入购物车" : "立即订购");
        tvCount.setText("1");
        typeDialog.show();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_close:
                if (typeDialog != null) {
                    typeDialog.dismiss();
                }
                break;
            case R.id.iv_minus:
                String countStr = tvCount.getText().toString().trim();
                int count = Integer.parseInt(countStr);
                if (count > 1) {
                    count--;
                }
                tvCount.setText("" + count);
                break;
            case R.id.iv_add:
                String countStr1 = tvCount.getText().toString().trim();
                int count1 = Integer.parseInt(countStr1);
                if (count1 < 100) {
                    count1++;
                }
                tvCount.setText("" + count1);
                break;
            case R.id.btn_ok:
                if (typeDialog != null) {
                    typeDialog.dismiss();
                }
                String btnStr = ((Button) v).getText().toString().trim();
                Integer selectCount = Integer.valueOf(tvCount.getText().toString());
                if (btnStr.equals("加入购物车")) {
//                    new HttpRequest<DefaultResponse>()
//                            .with(this)
//                            .setApiCode("_upshopcar_001")
//                            .addParam("userToken",MyApp.getInstance().getUserToken())
//                            .addParam("real_id", goodsDetail.getGoods_id())
//                            .addParam("num", 1)
//                            .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
//                                @Override
//                                public void onSuccess(BaseResponse response) {
//                                    toast("添加成功");
//                                }
//                            }).start(new DefaultResponse());
                } else if (btnStr.equals("立即订购")) {
                    ConfirmOrderActivity.open(this, goodsDetail, selectCount);
                }
                break;
        }
    }


}
